package com.app.oasystem.config;

import com.app.oasystem.utils.SessionUtil;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 8080
 * @Description 配置
 * @date 2021年01月18日 10:53:00
 */
@Configuration
public class FilterConfiguration {

    public FilterConfiguration() {
    }

    @Bean
    public FilterRegistrationBean myFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new SessionFilter());
        registration.addUrlPatterns(new String[]{"/*"});
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }

    class SessionFilter implements Filter {

        SessionFilter() {
        }

        @Override
        public void init(FilterConfig cfg) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            SessionUtil.setRequest(request);
            SessionUtil.setResponse(response);
            chain.doFilter(req, res);
            SessionUtil.removeThreadLocalRequest();
            SessionUtil.removeThreadLocalResponse();
        }

        @Override
        public void destroy() {
        }
    }
}